import EventEmitter from "events"

export class TextModel extends EventEmitter {
  private spacers_ = ""

  textChangeEmit_() {
    this.emit("text-change")
  }

  getSpacers() {
    return this.spacers_
  }

  getSpacersByIndex(startIndex: number, endIndex: number): string {
    return this.spacers_.slice(startIndex, endIndex)
  }

  insert(spacerIndex: number, spacers: string) {
    const oldSpacers = this.spacers_
    this.spacers_ =
      oldSpacers.slice(0, spacerIndex) + spacers + oldSpacers.slice(spacerIndex)

    this.textChangeEmit_()
  }

  remove(startIndex: number, endIndex: number) {
    const oldSpacers = this.spacers_
    if (startIndex > endIndex) {
      ;[startIndex, endIndex] = [endIndex, startIndex]
    }

    this.spacers_ = oldSpacers.slice(0, startIndex) + oldSpacers.slice(endIndex)

    this.textChangeEmit_()
  }
}

export default TextModel
